package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    // 微信登录url
    private static String wxloginUrl="https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    /**
     * 微信登录
     * @param code
     * @return
     */
    @Override
    public User wxLogin(String code) {
        // 1) 给微信发送请求,登录
        Map<String,String> param = new HashMap<>();
        param.put("appid",weChatProperties.getAppid());
        param.put("secret",weChatProperties.getSecret());
        param.put("js_code",code);
        param.put("grant_type","authorization_code");
            // 发送请求
        String json= HttpClientUtil.doGet(wxloginUrl, param);
        // 返回数据格式: {"session_key":"IBtMGVtADKlAlrSWmmyzkQ==","openid":"osvjO5YCjATodTaTB--QRmbgk-fc","unionid":"o5PB1s0ICGDkqy3oInh4qAJ_9YYI"}
        JSONObject jsonObject = JSON.parseObject(json); // 使用fastJson 转换
        // 2) 解析结果,获取OpenID
        String openid = (String)jsonObject.get("openid"); // 获取openid
        // 3) 判断是否是新用户
        User user  =userMapper.getByOpenid(openid);
        // 4) 如果是新用户,添加
        if(user==null){
            // 构建用户对象
            user=User.builder().openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();

            userMapper.insert(user);
        }
        // 5) 返回数据
        return user;
    }
}
